INPUT AND OUTPUT
Input and output (I/O) in Python refer to the process of interacting with the user or external data sources. Python provides built-in functions to read input from the user and display output to the screen or save it in files.
- Input (Reading User Input): In Python, you can use the
input()
function to read input from the user. Theinput()
function reads a line of text entered by the user and returns it as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
When the above code is executed, it will prompt the user to enter their name. The entered name will be stored in the name
variable, and the program will display a greeting message with the user's name.
- Output (Printing to the Screen): Python uses the
print()
function to display output on the screen. You can pass one or multiple values separated by commas to theprint()
function. It will convert the values to strings and display them.
Example:
age = 25
print("Your age is", age)
Output: Your age is 25
You can use string formatting to customize the output further:
name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
Output: Name: Alice, Age: 30
- File Input and Output: Python supports reading and writing data from/to files using file objects.
a. Reading from a file: To read data from a file, you can use the open()
function to open the file in read mode ("r"
) and then use the read()
method on the file object to read its contents.
Example:
# Assuming a file named "data.txt" with some content
with open("data.txt", "r") as file:
content = file.read()
print(content)
b. Writing to a file: To write data to a file, you can use the open()
function to open the file in write mode ("w"
) and then use the write()
method on the file object to write data into the file.
Example:
data = "This is some data to be written to the file."
with open("output.txt", "w") as file:
file.write(data)
These are the basic concepts of input and output in Python. By utilizing these functions and techniques, you can interact with users and external data files effectively in your Python programs.